from google.appengine.ext import webapp                                        
from google.appengine.ext.webapp.util import run_wsgi_app                      
import logging                                                                 
     
from StringIO import StringIO                                                  
import traceback
import xmlrpclib
from xmlrpcserver import XmlRpcServer
from google.appengine.ext import db
import datetime

class XmlRpcWrapper():
    """
    This class acts as a wrapper around a python object. It copies
    the underlying objects methods so they can be made avaliable to the XmlRpcServer class
    If the methods are public, the first argument "meta" is stripped off of the call from the 
    XMLRpcServer object, so that we can use a generic underlying object for the api call. 
    Private methods (i.e. those starting with an "_" are copied as is, as they are not exposed as
    remote procedures
    """
    def __init__(self, obj):
        self._obj=obj
        for a in dir(obj):
            m=getattr(obj, a)
            if callable(m) and a[0]!="_":
                    self.__dict__[a] = self._call_api_method(a)
                    self.__dict__[a].__doc__ = m.__doc__
                                
    def _call_api_method(self, method):
        return lambda meta, *args, **kwds: getattr(self._obj, method)(*args, **kwds)
    
def ascii_to_datetime(ascii_str):
    #http://www.tianya.cn/techforum/content/16/619502.shtml
    #floor 1095,only date,without time
    date_str=ascii_str
    if len(date_str) >12:
        return datetime.datetime.strptime(ascii_str,'%Y-%m-%d %H:%M:%S')
    else:
        return datetime.datetime.strptime(ascii_str,'%Y-%m-%d')
class Thread:
    thread_id="123456"
    name="thread"
    def __str__(self):
        return "Thread{thread_id:%s,name：%s}"%(self.thread_id,self.name)
    def __init__(self):
        self.thread_id="id"
        self.name="name"
        self.lst=['a.com','b.com','c.com']
    
                                                                                 
class Application:
    def __init__(self):
        pass                    
    def getThread(self):
        lst=[]
        t=Thread()
        lst.append(t)
        t.name="2"
        lst.append(t)
        return lst
    def getName(self):                                                    
        return 'example'
    def g(self):
        return ascii_to_datetime("2009-12-24 12:32:12")
    def get_None(self):
        return None
    def test(self):
        return ("abc","123")
class XMLRpcHandler(webapp.RequestHandler):                                    
    rpcserver = None
                                
    def __init__(self):         
        self.rpcserver = XmlRpcServer()                                        
        app = Application()                                                    
        self.rpcserver.register_class('app',XmlRpcWrapper(app))                               
                                                                               
    def post(self):
        request = StringIO(self.request.body)
        request.seek(0)                                                        
        response = StringIO()                                                  
        try:
            self.rpcserver.execute(request, response, None)                    
        except Exception, e:                                                   
            logging.error('Error executing: '+str(e))                          
            for line in traceback.format_exc().split('\n'):                    
                logging.error(line)
        finally:
            response.seek(0)  
                                                                               
        rstr = response.read()                                                 
        self.response.headers['Content-type'] = 'text/xml'                     
        self.response.headers['Content-length'] = "%d"%len(rstr)               
        self.response.out.write(rstr)
                                                                               
application = webapp.WSGIApplication(                                          
                                     [('/xmlrpc/', XMLRpcHandler)],
                                     debug=True)                               
def main():
  run_wsgi_app(application)                                                    
        
if __name__ == "__main__":
    main()